#include <stdio.h>
#include "main.h"
#include "mem.h"
#include "uart.h"
#include "funcBlock.h"
#include "funcBlock_VALUE.h"

struct fb_UPDOWN_VALUE
{
	uint8_t type;
	function_t func;
	uint8_t UP;
	uint8_t DOWN;
	uint8_t SEL;
	uint8_t Q16;
	uint16_t min;
	uint16_t max;
	uint16_t def;
	uint16_t val;
	uint8_t old_up_down;
};

void function_fb_UPDOWN_VALUE(struct funcBlock_t *_fb)
{
	struct fb_UPDOWN_VALUE *fb = (struct fb_UPDOWN_VALUE*)_fb;

	if ((getState(fb->SEL) == 0) || (fb->SEL == 0xFF)) // low Aktiv
	{
		// steigende Flanke an UP
		if ((getState(fb->UP) == 1) && ((fb->old_up_down & 0x01) == 0))
		{
			if (fb->val < fb->max)
				fb->val++;
		}
		
		// steigende Flanke an DOWN
		if ((getState(fb->DOWN) == 1) && ((fb->old_up_down & 0x02) == 0))
		{
			if (fb->val > fb->min)
				fb->val--;
		}
	}

	fb->old_up_down = 0;
	if (getState(fb->UP) == 1)
		fb->old_up_down = 0x01;
	if (getState(fb->DOWN) == 1)
		fb->old_up_down = 0x02;
	
	setBusValue_16b(fb->Q16, fb->val);
}

void set_fb_VALUE(uint8_t net, uint16_t value)
{
	if (net < NUM_16BIT_BUS)
	{
		//uart_puts("VALUE\n");
		setBusValue_16b(net, value);
	}
}

struct funcBlock_t* get_fb_UPDOWN_VALUE(uint8_t UP, uint8_t DOWN, uint8_t SEL, uint8_t Q16, uint16_t min, uint16_t max, uint16_t def)
{
	struct fb_UPDOWN_VALUE *fb = NULL;

	fb = (struct fb_UPDOWN_VALUE*)getMem(sizeof(struct fb_UPDOWN_VALUE));
	if (fb != NULL)
	{
		//uart_puts("UPDOWN_VALUE\n");
		fb->type = FB_TYPE_UPDOWN_VALUE;
		fb->func = function_fb_UPDOWN_VALUE;
		fb->UP = UP;
		fb->DOWN = DOWN;
		fb->SEL = SEL;
		fb->Q16 = Q16;
		fb->min = min;
		fb->max = max;
		fb->def = def;
		fb->val = def;
		fb->old_up_down = 0;
	}
	return (struct funcBlock_t*)fb;
}
